import {findKeyByValue} from "@/utils/util";
import OrgTreeSelect from "@/components/OrgTreeSelect/index.vue";
import {tabColumnsImport,assetNatureMap,mapAssetNature} from "./model.js";

export default {
    name: 'AssetMixIn',
    data(){
        return {
            tabColumnsImport,
            assetNatureMap,
            businessCode: 'AM01',
            tableData: [],
            searchTableData: [],
            exportList: [{columns: [], datas: []}], // 导入配置项
            importCheck: { // 导入字段对应
                模块名称: 'moduleName',
                用途及所用部位: 'usePart',
                软硬件名称: 'productName',
                品牌: 'brandName',
                规格型号及技术参数: 'specification',
                单位: 'unitName',
                数量: 'productCount',
                '单价(元)': 'unitPrice',
                '总价(元)': 'totalPrice',
                资产属性: 'assetNature'
            },
            form: {
                projectId: null,
                projectName: null,
                supplierName: '',
                setUpTime: '',
                schemeFile: [],
            },
            rules: {
                supplierName: [{required: true, message: '请输入供应商名称', trigger: 'blur'}],
                setUpTime: [{required: true, message: '请选择立项时间', trigger: 'blur'}],
                schemeFile: [{required: true, message: '请上传方案附件', trigger: 'blur'}],
            },
            searchArr: [
                {
                    name: '所属单位',
                    valueKey: 'org',
                    type: OrgTreeSelect,
                    isHasChildren: false,
                    isNeedAuth: false,

                },
                {
                    name: '模块名称',
                    value: 'moduleName',
                    type: 'input',
                    placeholder: '请输入模块名称'
                },
                {
                    name: '用途及所用部位',
                    value: 'usePart',
                    type: 'input',
                    placeholder: '请输入用途及所用部位'
                },
                {
                    name: '软硬件名称',
                    value: 'productName',
                    type: 'input',
                    placeholder: '请输入软硬件名称'
                },
                {
                    name: '资产属性',
                    value: 'assetNature',
                    type: 'select',
                    placeholder: '请选择资产属性',
                    data: [
                        {label: '可调拨', value: '0'},
                        {label: '利旧', value: '1'},
                        {label: '不可调拨', value: '2'},
                        {label: '可调拨/已转资产', value: '3'}
                    ]
                }
            ],
            queryParam: {},
            itemData: {},
            indexOfItem: 1,
            outSelectedRowKeys: [],
            viewMode: true,
            editModalVisible: false,
            loadingSubmit: false,
            loadingExport: false,
            loadingImport: false,

        }
    },
    methods:{
        mapAssetNature,
        findKeyByValue,
        search(val) {
            this.queryParam = val
            this.searchTableData = this.tableData.filter(item => {
                let res = true
                if (val.moduleName) {
                    res = res && item.moduleName.includes(val.moduleName)
                }
                if (val.usePart) {
                    res = res && item.usePart.includes(this.queryParam.usePart)
                }
                if (val.productName) {
                    res = res && item.productName.includes(this.queryParam.productName)
                }
                if (val.assetNature) {
                    res = res && +item.assetNature === +val.assetNature
                }
                return res
            })
            this.$refs.table.refresh()
        },
        async handleImport(e) {
            let form = await this.parseExcel(e)

            if (!this.queryParamIsEmpty) {
                this.queryParam = {}
                this.$nextTick(() => {
                    this.$refs.searchCom.handleReset()
                })
            }
            //console.log('excel=',form)
            this.tableData = this.tableData.concat(form)
            let columnsExport = this.$clone(this.tabColumnsImport)?.filter((i) => i.header !== '操作' && !i.isHidden)
            this.exportList = [
                {
                    successCount: 10,
                    columns: columnsExport,
                    datas: form
                }
            ]
            this.$refs.table.refresh(true)
        },

        parseExcel(e) {
            return new Promise((resolve, reject) => {
                let form = []
                for (let index in e) {
                    form.push({})

                    //excel中的每一行
                    let excelRow = e[index]

                    let listItem = form[index]
                    // 校验excel的表头字段
                    for (let i in this.importCheck) {
                        // item: cell表头中文对应的英文; key:excel 中cell的中文表头，val对应cell的值
                        let alphaKey = this.importCheck[i], wordKey = i, val = excelRow[i]

                        if (!Object.keys(excelRow).includes(wordKey) || !val || val === '') {
                            this.$message.warning(`第${Number(index) + 2}行【${i}】不能为空`)
                            this.loadingImport = false
                            return
                        }

                        //assetNature
                        let numberCol = ['productCount', 'unitPrice', 'totalPrice']
                        if (numberCol.includes(alphaKey)) {

                            if (isNaN(Number(val))) {
                                this.$message.warning(`第${Number(index) + 2}行【${i}】不是合法的数字`)
                                this.loadingImport = false
                                return
                            }

                            if (Number(val) <= 0) {
                                this.$message.warning(`第${Number(index) + 2}行【${i}】=${val}不能小于0`)
                                this.loadingImport = false
                                return
                            }
                            if(alphaKey !== 'productCount'){
                                val = Number(val).toFixed(2)
                            }
                        }
                        if (alphaKey === 'assetNature') {
                            if (!Array.from(this.assetNatureMap.values()).includes(val)) {
                                this.$message.warning(`第${Number(index) + 2}行【${i}】只能取以下值:【${[...this.assetNatureMap.values()]}】`)
                                this.loadingImport = false
                                return
                            }
                            val = findKeyByValue(this.assetNatureMap,val)
                        }
                        listItem[alphaKey] = val
                        listItem['index'] = this.indexOfItem++
                    }
                }
                this.loadingImport = false
                resolve(form);
            })
        },
        selectPreOrg(val) {
            if (val && val.length) {
                const lastValue = val[val.length - 1]
                //console.log('lastValue=',lastValue)
                if (lastValue.tageCode === 'PD' && lastValue.projectId) {
                    this.form.projectId = lastValue.projectId
                    this.form.projectName = lastValue.projectName
                } else {
                    this.$message.warn("请选择项目，而不是分公司")
                }
            }
        },
    },
    computed: {
        //有搜索参数的时候展示搜索数据集
        queryParamIsEmpty: function () {
            return Object.keys(this.queryParam).filter(i => i !== "org").length === 0
        }
    },
    watch: {
        itemData: function (newVal, val) {
            console.log('itemData=', newVal)
        }
    }
}